package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.feignService.TaskService;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


//自动补货任务生成job
@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService machineService;

    @Autowired
    private TaskService taskService;

    /*
    * 售货机扫描任务
    * */
    @XxlJob("supplyJobHandler")
    public ReturnT<String> supplyHandler(String param){

        //获取分片总数和当前分片索引
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        int total = shardingVo.getTotal(); //分片总数
        int index = shardingVo.getIndex(); //当前分片索引
        log.info("分片参数 当前分片索引{} 总分片数{}",index,total);
        XxlJobLogger.log("分片参数 当前分片索引"+index+" 总分片数"+total);

        Integer percent = taskService.getSupplyAlertValue();

        //查询所有运行状态下的售货机
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                .apply("mod(id,"+total+")="+index); //对id取模
        List<VendingMachineEntity> list = machineService.list(queryWrapper);
        list.forEach(vm->{
            XxlJobLogger.log("扫描售货机"+vm.getInnerCode());
            //扫描售货机货道的逻辑
            int inventory = machineService.inventory(percent, vm);
            if (inventory>0){
                XxlJobLogger.log("售货机："+vm.getInnerCode()+"缺货");
            }
            // 发送补货消息
            machineService.sendSupplyTask(vm);
        });
        return ReturnT.SUCCESS;
    }
}
